import React from 'react';
import { Button, DatePicker, Space } from 'tdesign-react';
import dayjs from 'dayjs';

interface DateSwitcherProps {
  value: string; // 'YYYY-MM-DD'
  onChange: (date: string) => void;
}

const DateSwitcher: React.FC<DateSwitcherProps> = ({ value, onChange }) => {
  const today = dayjs().startOf('day');
  const minDay = today.add(1, 'day'); // 明天
  const maxDay = today.add(7, 'day'); 
  const current = dayjs(value);

  // 判断按钮是否可用
  const canPrev = current.isAfter(minDay, 'day');
  const canNext = current.isBefore(maxDay, 'day');

  // 切换日期
  const handleChange = (days: number) => {
    const newDate = current.add(days, 'day');
    if (newDate.isBefore(minDay, 'day') || newDate.isAfter(maxDay, 'day')) return;
    onChange(newDate.format('YYYY-MM-DD'));
    PubSub.publish('updateSelectedDate', newDate.format('YYYY-MM-DD'));
  };

  // 只允许选择范围内的日期
  const disabledDate = (date: any) => {
    const d = dayjs(date);
    return d.isBefore(minDay, 'day') || d.isAfter(maxDay, 'day');
  };

  return (
    <Space style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', position: "relative", top: -20 }}>
      <Button size="small" onClick={() => handleChange(-1)} disabled={!canPrev}>前一天</Button>
      <DatePicker
        value={value}
        onChange={(val) => {
          let dateStr = '';
          if (typeof val === 'string') {
            dateStr = val;
          } else if (val && typeof val === 'object' && 'format' in val && val.format instanceof Function) {
            dateStr = val.format('YYYY-MM-DD');
          }
          if (dateStr) onChange(dateStr);
        }}
        style={{ width: 220 }}
        format="YYYY-MM-DD"
        mode="date"
        clearable={false}
        disableDate={disabledDate}
      />
      <Button size="small" onClick={() => handleChange(1)} disabled={!canNext}>后一天</Button>
    </Space>
  );
};

export default DateSwitcher; 